<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>签名</title>
</head>
<body>

<div style="text-align: center; ">
    <h1>签名区</h1>
    <canvas></canvas>

    <div>
        <p>
            <button class="submit">提交签名</button>
            <button class="clear">清空签名</button>
        </p>


    </div>
</div>


</body>
</html>

<style>
    canvas {
        background-color: #42b983;
        margin: 10px;
        box-shadow: 0 0 4px #aaa;
        cursor: pointer;
    }
</style>

<script>
    // 获取canvas元素
    let cvs = $("canvas");
    // 获取画笔工具对象
    let ctx = cvs.getContext('2d');
    cvs.onmousedown = e => {
        // 开始绘制名字
        ctx.beginPath();
        // 将画笔起点设置为当前位置
        ctx.moveTo(e.offsetX, e.offsetY);
        cvs.onmousemove = ev => {
            //画笔跟着鼠标绘制线
            ctx.lineTo(ev.offsetX, ev.offsetY)
            //上色
            ctx.strokeStyle = '#000'
            ctx.stroke()
        }
    }

    cvs.onmouseup = () => cvs.onmousemove = null



    $(".clear").onclick = () => ctx.clearRect(0, 0, cvs.width, cvs.height)

    $(".submit").onclick = () => {

        // 借助a标签实现下载
        let aEl = document.createElement('a');
        aEl.href = cvs.toDataURL('image/jpg', 1);
        aEl.download = '签名'
        aEl.innerText = '下载';
        $("body").appendChild(aEl).click();
        aEl.remove()
    }

    function $(select) {
        return document.querySelector(select);
    }
</script>